<meta charset="utf-8">
<?php
// edit.php?week_number=<number>&day=<number>&section=<number>&name=<string>&location<string>

// 判断参数是否完整
if (!isset($_GET['week_number']) || $_GET['week_number'] <= 0 || !isset($_GET['day']) || $_GET['day'] <= 0 || !isset($_GET['section']) || $_GET['section'] <= 0) {
	die('参数错误');
}

// 查询课程表指定时间的课程信息
include_once('database.php');
$sql = "SELECT name,location FROM courses WHERE week_number=${_GET['week_number']} && day=${_GET['day']} && section=${_GET['section']}";
$result = @mysqli_query($connection, $sql) or die("查询课程表失败: ".mysqli_error($connection));

// 判断是否已修改完成
if (isset($_GET['name']) && isset($_GET['location'])) {
	// 去首尾空格符
	$_GET['name'] = trim($_GET['name']);
	$_GET['location'] = trim($_GET['location']);

	if (mysqli_num_rows($result) > 0) {
		if (strlen($_GET['name']) == 0) {
			// 记录存在，但课程名为空时，删除记录
			$sql = "DELETE FROM courses WHERE week_number=${_GET['week_number']} && day=${_GET['day']} && section=${_GET['section']}";
		} else {
			// 记录存在，且课程名不为空时，更新记录
			$sql = "UPDATE courses SET name='${_GET['name']}',location='${_GET['location']}' WHERE week_number=${_GET['week_number']} && day=${_GET['day']} && section=${_GET['section']}";
		}
	} elseif (strlen($_GET['name']) > 0) {
		// 记录不存在，且课程名不为空时，插入记录
		$sql = "INSERT INTO courses(week_number,day,section,name,location) VALUES(${_GET['week_number']},${_GET['day']},${_GET['section']},'${_GET['name']}','${_GET['location']}')";
	}

	@mysqli_query($connection, $sql) or die("操作课程表失败: ".mysqli_error($connection));
	header("Location: table.php?action=edit&week_number=${_GET['week_number']}");
}

$course = mysqli_fetch_array($result, MYSQLI_ASSOC);
?>

<!DOCTYPE html>
<html>
<head>
	<style type="text/css">
		table {
			margin: auto;
		}
		.action {
			padding: 16px 8px;
			text-align: center;
		}
		.action > * {
			margin: 0 8px;
		}
	</style>
</head>
<body>
	<form>
		<input hidden="hidden" name="week_number" value="<?php echo $_GET['week_number']; ?>">
		<input hidden="hidden" name="day" value="<?php echo $_GET['day']; ?>">
		<input hidden="hidden" name="section" value="<?php echo $_GET['section']; ?>">
		<table>
			<tr>
				<td>课程名：</td>
				<td>
					<input type="text" name="name" value="<?php echo $course['name']; ?>">
				</td>
			</tr>
			<tr>
				<td>上课地点：</td>
				<td>
					<input type="text" name="location" value="<?php echo $course['location']; ?>">
				</td>
			</tr>
			<tr>
				<td class="action" colspan="2">
					<a href="<?php echo "table.php?action=edit&week_number=${_GET['week_number']}" ?>">返回</a>
					<input type="submit" value="完成">
				</td>
			</tr>
		</table>
	</form>
</body>
</html>